package com.eqdd.yiqidian.ui.gongneng.kehu

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.view.View
import android.widget.TextView
import com.amap.api.location.AMapLocation
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.MyFragmentPagerAdapter
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.rebuild.ClientResultBean
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonCallBack
import com.eqdd.yiqidian.kotlin.bottomDialog
import com.eqdd.yiqidian.kotlin.popMenu
import com.eqdd.yiqidian.service.LocationObservable
import com.eqdd.yiqidian.ui.gongneng.kehu.fragment.ContantsFragment
import com.eqdd.yiqidian.ui.gongneng.kehu.fragment.FeedbackRecordFragment
import com.eqdd.yiqidian.ui.gongneng.kehu.fragment.SalesChanceFragment
import com.eqdd.yiqidian.ui.gongneng.kehu.fragment.VisitRecordFragment
import com.eqdd.yiqidian.utils.ToastUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.activity_customer_manager.*
import kotlinx.android.synthetic.main.activity_title.*
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import java.lang.Exception
import java.util.*
import kotlin.collections.ArrayList

/**
 * 客户管理
 * Created by jhj on 18-5-17.
 */

class CustomerManagerActivity : BaseActivity() {


    internal var title = ArrayList<String>()
    internal var mFragments: MutableList<Fragment>? = null
    private var customerId: Int = 0
    private var customerName: String? = null
    var pi = 3.1415926535897932384626


    internal var addClasses = arrayOf<Class<*>>(AddSaleChanceActivity::class.java, AddHuifangRecordActivity::class.java, AddFankuiRecordActivity::class.java, AddLianxirenActivity::class.java)
    internal var requestCode = intArrayOf(Config.ADD_XIAOSHOU_RECORD, Config.ADD_HUIFANG_RECORD, Config.ADD_FANKUI_RECORD, Config.ADD_LIANXIREN)

    override fun initBinding() {
        setContentView(R.layout.activity_customer_manager)
        initTopTitleBar(View.VISIBLE, "客户管理")
        customerId = intent.getIntExtra(Config.ID, -1)
        customerName = intent.getStringExtra(Config.CLIENT_NAME)
        if (customerId == -1) {
            ToastUtil.showShort("获取客户信息失败")
            finish()
        }

        iv_right.visibility = View.VISIBLE
        iv_right.imageResource = R.mipmap.addg
        popMenu(arrayListOf("客户详情", "到客户那去"), iv_right) { dialog, pos ->
            when (pos) {
                0 -> {
                    startActivity<UpdateKehuActivity>(Config.ID to customerId, Config.CLIENT_NAME to customerName)
                }
                1 -> {
                    routePlanning()
                }


            }

        }

        appBarLayout?.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            appBarLayout?.isEnabled = verticalOffset >= 0
        }
    }

    private var mapLocation: AMapLocation? = null

    override fun initData() {
        RxPermissions.getInstance(this).request(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe { isGrant ->
                    LocationObservable.get().subscribe { aMapLocation ->
                        if (aMapLocation.errorCode == 0) {
                            mapLocation = aMapLocation
                        }
                    }
                }
    }

    private var bean: ClientResultBean? = null

    override fun setView() {
        OkGo.post<HttpResult<ClientResultBean>>(HttpConfig.BASE_URL + HttpConfig.CLENT_INFO)
                .params("owner", user.guid)
                .params("cusid", customerId)
                .execute(object : JsonCallBack<HttpResult<ClientResultBean>>() {

                    override fun onSuccess(response: Response<HttpResult<ClientResultBean>>) {
                        val httpResult = response.body()
                        if (httpResult.status == 200) {
                            bean = httpResult.items
                            tv_name?.text = bean?.cusName
                            tv_position?.text = String.format(Locale.CHINA, "地址：%s", bean?.address)
                            tv_phone?.text = String.format(Locale.CHINA, "电话：%s", bean?.cusCall)
                            tv_phone?.setOnClickListener { v ->
                                val intent = Intent(Intent.ACTION_DIAL)
                                val uri = Uri.parse("tel:" + (v as TextView).text.toString())
                                intent.data = uri
                                startActivity(intent)
                            }
                        }
                    }
                })


        title.add("销售机会")
        title.add("回访记录")
        title.add("反馈记录")
        title.add("联系人")
        mFragments = ArrayList()
        mFragments?.add(getFragment(SalesChanceFragment()))
        mFragments?.add(getFragment(VisitRecordFragment()))
        mFragments?.add(getFragment(FeedbackRecordFragment()))
        mFragments?.add(getFragment(ContantsFragment()))
        viewpager?.adapter = MyFragmentPagerAdapter(supportFragmentManager, title, mFragments)
        tabs?.setupWithViewPager(viewpager)

        tv_add.text = "新增销售机会"
        tv_add.onClick {
            val bundle = Bundle()
            bundle.putString("cusid", customerId.toString() + "")
            bundle.putString(Config.CLIENT_NAME, customerName)
            startActivityForResult(addClasses[0], bundle, requestCode[0])
        }
        viewpager.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                tv_add.visibility = View.VISIBLE
                tv_add.text = when (position) {
                    0 -> "新增销售机会"
                    1 -> "新增回访记录"
                    2 -> "新增反馈记录"
                    3 -> "新增联系人"
                    else -> {
                        tv_add.visibility = View.GONE
                        ""
                    }
                }
                tv_add.onClick {
                    val bundle = Bundle()
                    bundle.putString("cusid", customerId.toString() + "")
                    bundle.putString(Config.CLIENT_NAME, customerName)
                    startActivityForResult(addClasses[position], bundle, requestCode[position])
                }

            }

        })


    }


    fun getFragment(fragment: Fragment): Fragment {
        val bundle = Bundle()
        bundle.putString("cusid", customerId.toString() + "")
        bundle.putString(Config.CLIENT_NAME, customerName)
        fragment.arguments = bundle
        return fragment
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        viewpager?.currentItem?.let {
            mFragments?.get(it)?.onActivityResult(requestCode, resultCode, data)
        }
    }


    fun routePlanning() {
        bottomDialog(arrayListOf("高德地图", "百度地图")) {
            when (it) {
                1 -> {
                    try {
                        val intent = Intent()
                        intent.action = Intent.ACTION_VIEW
                        intent.addCategory(Intent.CATEGORY_DEFAULT)
                        //将功能Scheme以URI的方式传入data
                        val uri = Uri.parse(mapUri("gaode"))
                        intent.data = uri
                        //启动该页面即可
                        startActivity(intent)
                    } catch (e: Exception) {
                        toast("没有安装高德地图")
                    }
                }
                2 -> {
                    try {
                        val intent = Intent()
                        intent.setData(Uri.parse(mapUri("baidu")))
                        startActivity(intent)
                    } catch (e: Exception) {
                        toast("没有安装百度地图")
                    }
                }
            }
        }


    }

    fun mapUri(type: String): String {
        return if (type == "baidu") {
            if (bean?.addrlong != null && bean?.addrlat != null) {
                val array = gcj02_To_Bd09(bean?.addrlong!!, bean?.addrlat!!)
                "baidumap://map/direction" +
                        "?destination=${array[0]},${array[1]}" +
                        "&sy=0" +
                        "&mode=driving" +
                        "&src=andr.baidu.openAPIdemo"
            } else {
                ""
            }
        } else if (type == "gaode") {
            "amapuri://route/plan/" +
                    "?sid=BGVIS1" +
                    "&slat=${mapLocation?.latitude}" +
                    "&slon=${mapLocation?.longitude}" +
                    "&sname=${mapLocation?.address}" +
                    "&did=BGVIS2" +
                    "&dlat=${bean?.addrlong}" +
                    "&dlon=${bean?.addrlat}" +
                    "&dname=${bean?.address}" +
                    "&dev=0" +
                    "&t=0"
        } else {
            ""
        }
    }

    fun gcj02_To_Bd09(gg_lat: Double, gg_lon: Double): ArrayList<Double> {
        val x = gg_lon
        val y = gg_lat
        val z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * pi)
        val theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * pi)
        val bd_lon = z * Math.cos(theta) + 0.0065
        val bd_lat = z * Math.sin(theta) + 0.006
        return arrayListOf<Double>(bd_lat, bd_lon)
    }
}